package com.zyg.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.common.ResultCode;
import com.zyg.dao.SysFileMapper;
import com.zyg.model.Result;
import com.zyg.pojo.SysFile;
import com.zyg.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Calendar;

/**
 * @author: 牛二
 * @date: 2020/8/20 17:56
 * @email: 550354312@qq.com
 * @project: zyg_project_demo
 * @describe:
 */
@Slf4j
@Service
@Transactional
public class FileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements FileService {

    @Value("${zyg-file.file-path}")
    private String filePath;

    /**
     * 文件保存
     * 1、获取文件的信息
     * 2、保存文件
     * @param multipartFile
     * @return
     */
    @Override
    public Result saveFile(MultipartFile multipartFile) {

        //判断文件夹是否存在，不存在生成文件路径
        String relativePath = getRelativePath();
        String rootPath = existFilePath(relativePath);
        if (multipartFile == null || multipartFile.isEmpty()) {
            log.error("上传的文件为空！！！");
            return new Result().initCodeAndMsg(ResultCode.FILE_UPLOAD_ERR_IS_NULL);
        }

        //保存文件
        try {
            SysFile sysFile = new SysFile();
            sysFile.setRootPath(filePath);
            //文件名
            String fileCompleteName = multipartFile.getOriginalFilename();
            String fileName = fileCompleteName.split("\\.")[0];
            //文件后缀名
            String extendName = fileCompleteName.split("\\.")[1];
            //获取contentType
            String contentType = multipartFile.getContentType();
            //文件大小，单位为KB
            Long fileSize =  multipartFile.getSize();

            log.info("fileName：{}",fileName);
            sysFile.setFileName(fileName);
            log.info("extendName：{}",extendName);
            sysFile.setExtendName(extendName);
            log.info("contentType：{}",contentType);
            sysFile.setContextType(contentType);
            log.info("fileSize：{}",fileSize);
            sysFile.setFileSize(new BigDecimal(fileSize));
            String fileSign =  System.currentTimeMillis() + "";
            sysFile.setFileSign(fileSign);
            String newFileName = fileSign + "." + extendName;
            sysFile.setRelativePath(relativePath);
            //保存文件
            File dest = new File(rootPath + "\\" + newFileName );
            multipartFile.transferTo(dest);
            baseMapper.insert(sysFile);
            log.info("保存后的文件名：" + newFileName);
            return new Result().initSuccess();

        } catch (IOException e) {
            e.printStackTrace();
            return new Result().initCodeAndMsg(ResultCode.FILE_UPLOAD_ERR);
        }

    }

    /**
     * 生成文件路径
     * @param relativePath
     * @return
     */
    private String existFilePath(String relativePath){
        String nowFilePath = filePath + "\\" + relativePath ;
        File file = new File(nowFilePath);
        if (!file.exists()) {
            log.info("文件目录不存在生成文件！");
            file.mkdirs();
        }
        return nowFilePath;
    }

    /**
     * 生成相对路径
     * @return
     */
    private String getRelativePath(){
        Calendar calendar = Calendar.getInstance();//使用日历类
        int year = calendar.get(Calendar.YEAR);//得到年
        int month = calendar.get(Calendar.MONTH)+1;//得到月，因为从0开始du的，所以要加zhi1
        int day = calendar.get(Calendar.DAY_OF_MONTH);//得到天
        String relativePath = year + "\\" + month + "\\" + day;
        return relativePath;
    }

    @Override
    public void getFileById(String id, HttpServletResponse response) {
        SysFile sysFile = baseMapper.selectById(id);
        try {
            String fileCompletePath = sysFile.getRootPath() + "\\" + sysFile.getRelativePath() + "\\" + sysFile.getFileSign() +"."+ sysFile.getExtendName();
            System.out.println(fileCompletePath);
            FileInputStream inputStream = new FileInputStream(fileCompletePath);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            response.setContentType(sysFile.getContextType());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + sysFile.getFileName() + sysFile.getExtendName() + "\"");
            System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length - 1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            OutputStream os = response.getOutputStream();
            os.write(data);
            //先声明的流后关掉！
            os.flush();
            os.close();
            inputStream.close();

        } catch (Exception e) {
            log.error("文件下载错误！");
            e.printStackTrace();
        }
    }

    /**
     * 文件类型转换
     * @param id
     * @param response
     */
    @Override
    public void getFileConversion(String id, HttpServletResponse response) {
        //判断文件类型是否为word 和 excel
        toPdf();
    }

    private String toPdf(){
        /**
         * 需要安装OpenOffice
         * 引用JobConverter.jar包
         */

//        // 调用openoffice服务线程
//        /** 我把openOffice下载到了 C:/Program Files (x86)/下  ,下面的写法自己修改编辑就可以**/
//        String command = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
//        Process p = Runtime.getRuntime().exec(command);
//
//        // 连接openoffice服务
//        OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
//        connection.connect();
//
//        // 转换
//        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
//        converter.convert(inputFile, outputFile);
//
//        // 关闭连接
//        connection.disconnect();
//
//        // 关闭进程
//        p.destroy();
        return null;
    }
}
